package com.heima.juc.unlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntUnaryOperator;

/**
 * @author : leimingchao
 * @date Date : 2022年02月12日 16:30
 */
@Slf4j(topic = "c.Test1")
public class Test1 {

    public static void main(String[] args) {

        AtomicInteger atomicInteger = new AtomicInteger(5);

        //等价于 ++i
        //System.out.println(atomicInteger.incrementAndGet());

        //等价于 i++
        //System.out.println(atomicInteger.getAndIncrement());

        //等价于 --i
        //System.out.println(atomicInteger.decrementAndGet());

        //等价于 i--
        //System.out.println(atomicInteger.getAndDecrement());


        //System.out.println(atomicInteger.getAndAdd(5));

        //System.out.println(atomicInteger.addAndGet(5));

        // 先修改再获取            读取到    设置值
        // atomicInteger.updateAndGet(value -> value * 10);

        // 先获取再修改            读取到    设置值
        // atomicInteger.getAndUpdate(value -> value * 10);

        System.out.println(updateAndGet(atomicInteger, p -> p / 2));

        System.out.println(atomicInteger.get());
    }

    public static int updateAndGet(AtomicInteger atomicInteger, IntUnaryOperator operator) {

        while (true) {
            int prev = atomicInteger.get();

            int next = operator.applyAsInt(prev);

            if (atomicInteger.compareAndSet(prev, next)) {
                return next;
            }
        }
    }
}
